package com.avic.rong.questionOrAnswer;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;



/**
 * @author dust
 * @function  js传参时候使用
 * @created at 2019/3/6
 */
public class JSToolX5 {

    private Activity activity;
    private WebView webView;

    public JSToolX5(Activity activity, WebView webView) {
        this.activity = activity;
        this.webView = webView;
    }


    /**
     * 调用JS函数，动态拼装调用参数 webView.loadUrl("javascript:setCreated('" + content.getTime() + "')");
     *
     * @param action
     * @param params
     */
    public void invokeJs(final String action, final Object... params) {
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (TextUtils.isEmpty(action)) {
                    return;
                }
                StringBuffer urlSb = new StringBuffer("javascript:" + action + "(");
                StringBuffer paramsSb = new StringBuffer("");
                if (params != null) {
                    for (int i = 0; i < params.length; i++) {
                        Object obj = params[i];
                        String str = String.valueOf(obj);
                        paramsSb.append("'" + str + "',");
                    }
                }
                if (!TextUtils.isEmpty(paramsSb.toString())) {
                    urlSb.append(paramsSb.deleteCharAt(paramsSb.length() - 1));
                }
                urlSb.append(")");
                if (webView != null) {
                    String script = urlSb.toString();
                    Log.i("JSTool", "script:" + script);
                    webView.loadUrl(script);
                }
            }
        });
    }
}
